package com.hyhy.hycloud.commons.helper;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;

import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lanpengfei
 * @date 2019-01-09
 */
public class HycloudLocalTimeDeserializer extends LocalTimeDeserializer implements DateFormatHelper {

    private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_TIME;
    public static final HycloudLocalTimeDeserializer INSTANCE = new HycloudLocalTimeDeserializer();

    public HycloudLocalTimeDeserializer() {
        this(DEFAULT_FORMATTER);
    }

    public HycloudLocalTimeDeserializer(DateTimeFormatter formatter) {
        super(formatter);
    }

    @Override
    public LocalTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        if (parser.hasToken(JsonToken.VALUE_STRING)) {
            String source = parser.getText().trim();
            DateTimeFormatter dateTimeFormatter = initDateTimeFormatter(source);
            if (dateTimeFormatter != null) {
                return LocalTime.parse(source, dateTimeFormatter);
            }
        }

        return super.deserialize(parser, context);
    }
}
